<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="elForm"
      size="small"
      :inline="true"
      style="margin-top: 10px"
      label-width="68px"
    >
      <el-form-item label="插座编号" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入插座编号"
          clearable
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item label="继电器状态" prop="workStatus">
        <el-select
          v-model="queryParams.workStatus"
          placeholder="请选择设备继电器状态"
          clearable
          :style="{ width: '100%' }"
        >
          <el-option label="开" value="1"></el-option>
          <el-option label="关" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间段" prop="searchTimeSlot">
        <el-date-picker
          v-model="queryParams.searchTimeSlot"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-button
        type="primary"
        style="margin-left: 10px"
        icon="el-icon-search"
        size="mini"
        @click="submitSearchForm"
        >搜索</el-button
      >
      <el-button icon="el-icon-refresh" size="mini" @click="resetForm"
        >重置</el-button
      >
      <el-button icon="el-icon-refresh" size="mini" @click="exportExcel1" >导出报表</el-button>
    </el-form>

    <el-row>
      <div class="el-table el-table--enable-row-hover el-table--medium">
        <div ref="devInfo" style="height: 320px" />
      </div>
    </el-row>
    <el-row>
      <el-table :data="devHistoryList" style="width: 100%">
        <el-table-column
          prop="deviceId"
          label="设备编号"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="voltage" label="总电压" align="center">
        </el-table-column>
        <el-table-column prop="electricCurrent" label="总电流" align="center">
        </el-table-column>
        <el-table-column prop="activePower" label="总有功功率" align="center">
        </el-table-column>
        <el-table-column prop="frequency" label="总频率" align="center">
        </el-table-column>
        <el-table-column prop="powerFactor" label="总功率因数" align="center">
        </el-table-column>
        <el-table-column prop="energy" label="累计用电量" align="center">
        </el-table-column>
        <el-table-column prop="workStatus" label="继电器状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.workStatus == 1">开</span>
            <span v-else-if="scope.row.workStatus == 0">关</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="creatTime"
          label="添加时间"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            {{ dateFormat(scope.row.creatTime / 1000) }}
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row style="margin-bottom: 10px">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getHistoryList"
      />
    </el-row>
  </div>
</template>
<script>
import { getDevHistoryList , exportExcelByquery } from "@/api/alm/dev-use-power/dev-history-info/dev-history-info";
import * as echarts from "echarts";
import { getType } from "@/api/devTypeMap";

export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ipaddr: undefined,
        userName: undefined,
        status: undefined,
      },
      dateRange: [],
      devHistoryList: [],
      devInfo: null,
      // searchTimeSlot: []
    };
  },
  created() {
    //  this.getHistoryList();
  },
  deactivated() {},
  mounted() {},
  methods: {
    getHistoryList() {
      getDevHistoryList(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((res) => {
        if (res.total == 0) {
          this.$message.warning("没有记录！");
          return;
        }
        this.devHistoryList = res.rows;
        this.total = res.total;
        this.getDevInfo();
      });
    },
    exportExcel1(){
      if (
        this.queryParams.searchTimeSlot &&
        this.queryParams.searchTimeSlot.length > 0
      ) {
        let timeArr = [];
        this.queryParams.searchTimeSlot.forEach((time) => {
          if (time instanceof Date) {
            timeArr.push(time.getTime());
          }
        });
        if (timeArr.length > 0) {
          this.queryParams.searchTimeSlot = timeArr;
        }
      }
      this.download('/alm/dev/hisinfo/export', {
        ...this.queryParams
      }, `历史数据导出.xlsx`)
      // 直接调用导入的 exportExcelByquery 函数
    
    },
    loadTime() {
      let obj = this.optTimeInfo();
      console.log("obj ", obj);
      let arr = [];
      if (obj) {
        for (let devHistory of this.devHistoryList) {
          if (this.contrastTime(devHistory, obj)) {
            arr.push(devHistory);
          }
        }
        console.log("arr ", arr);
        this.devHistoryList = arr;
      }
    },

    contrastTime(devHistoryInfo, obj) {
      return (
        Number(devHistoryInfo.creatTime) > Number(obj.startTime) &&
        Number(devHistoryInfo.creatTime) < Number(obj.endTime)
      );
    },

    submitSearchForm() {
      if (
        this.queryParams.searchTimeSlot &&
        this.queryParams.searchTimeSlot.length > 0
      ) {
        let timeArr = [];
        this.queryParams.searchTimeSlot.forEach((time) => {
          if (time instanceof Date) {
            timeArr.push(time.getTime());
          }
        });
        if (timeArr.length > 0) {
          this.queryParams.searchTimeSlot = timeArr;
        }
      }
      console.log(this.queryParams);
      this.getHistoryList(this.queryParams);
    },

    resetForm() {
      this.$refs["elForm"].resetFields();
      this.queryParams = {};
      this.getHistoryList();
    },
    dateFormat(timeStamp) {
      // 创建一个新的Date对象，将时间戳作为参数传递给构造函数
      const date = new Date(timeStamp * 1000);
      // 获取年、月、日、小时和分钟
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      // 重新赋值格式化后的日期字符串
      return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    },

    optTimeInfo() {
      if (
        this.queryParams.searchTimeSlot &&
        this.queryParams.searchTimeSlot.length > 0
      ) {
        let startTime = this.queryParams.searchTimeSlot[0];
        let endTime = this.queryParams.searchTimeSlot[1];
        return {
          startTime: startTime.getTime(),
          endTime: endTime.getTime(),
        };
      }

      return false;
    },

    getDevInfo() {
      if (!echarts.getInstanceByDom(this.$refs.devInfo)) {
        this.devInfo = echarts.init(this.$refs.devInfo, "macarons");
      }
      let opt = {
        title: {
          text: " ",
          subtext: "",
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["电压", "电流", "功率", "功率因数", "用电量"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          // data: ['18:01:23', '18:21:23', '18:31:23', '18:41:23', '18:51:23', '18:54:23', '18:56:23']
          data: [],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "电压",
            type: "line",
            data: [],
            itemStyle: {
              normal: {
                color: '#607bca', //改变折线点的颜色
                lineStyle: {
                color: '#607bca' //改变折线颜色
                }
              }
            },
          },
          {
            name: "电流",
            type: "line",
            data: [],
            itemStyle: {
              normal: {
                color: '#93cd77', //改变折线点的颜色
                lineStyle: {
                color: '#93cd77' //改变折线颜色
                }
              }
            },
          },
          {
            name: "功率",
            type: "line",
            data: [],
            itemStyle: {
              normal: {
                color: '#fac859', //改变折线点的颜色
                lineStyle: {
                color: '#fac859' //改变折线颜色
                }
              }
            },
          },
          {
            name: "功率因数",
            type: "line",
            data: [],
            itemStyle: {
              normal: {
                color: '#ee6a6a', //改变折线点的颜色
                lineStyle: {
                color: '#ee6a6a' //改变折线颜色
                }
              }
            },
          },
          {
            name: "用电量",
            type: "line",
            data: [],
            itemStyle: {
              normal: {
                color: '#73c0de', //改变折线点的颜色
                lineStyle: {
                color: '#73c0de' //改变折线颜色
                }
              }
            },
          },
        ],
      };

      

      let i = 0;
      for (let devHistory of this.devHistoryList) {
        opt.series[0].data.push(devHistory.voltage);
        opt.series[1].data.push(devHistory.electricCurrent);
        opt.series[2].data.push(devHistory.activePower);
        opt.series[3].data.push(devHistory.powerFactor);
        opt.series[4].data.push(devHistory.energy);
        opt.xAxis.data.push(this.dateFormat(devHistory.creatTime / 1000));
        opt.title.subtext = devHistory.deviceId.toUpperCase();
      }
      this.devInfo.setOption(opt);
      window.addEventListener("resize", () => {
        this.devInfo.resize();
      });
    },
  },
};
</script>

<style scoped></style>